package com.lg.distributed.transaction.rabbit;

import com.lg.distributed.transaction.config.MyMQConfig;
import com.lg.distributed.transaction.domain.MqMessage;
import com.lg.distributed.transaction.domain.SendMessage;
import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author by Mr. Li 2020/12/11 11:02
 */
@Slf4j
@Component
public class MyRabbitListener {
    //@RabbitHandler
    @RabbitListener(queues = {MyMQConfig.DISTRIBUTED_TRANSACTION_QUEUE})
    public void listener(MqMessage sendMessage, Message message,
                         Channel channel) {

        try {
            channel.basicQos(1); // 一次处理一个请求
            final Consumer consumer = new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    String message = new String(body, StandardCharsets.UTF_8);
                    log.info("[x] Received ' {} '", message);
                    try {
                        log.info("consumer is success!!!");

                    } finally {
                        // 确认收到信息
                        channel.basicAck(envelope.getDeliveryTag(), false);
                    }
                }
            };

            byte[] body = message.getBody();

            System.out.println("接受到消息..." + sendMessage);
            MessageProperties messageProperties = message.getMessageProperties();
            messageProperties.getHeaders();

            log.info("[信息接受成功！]");
            //channel.basicConsume(MyMQConfig.DISTRIBUTED_TRANSACTION_QUEUE, false, consumer); 这种事应答，然是将消息重新放到队列中。再次发送
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            log.error("信息消费失败");
        }
    }
}
